package com.jiangli.service.Search.Impl;

import com.jiangli.entity.Dish;
import com.jiangli.entity.Ingredient;
import com.jiangli.mapper.DishMapper;
import com.jiangli.mapper.IngredientMapper;
import com.jiangli.utils.Sreach.RedisKeyUtils;
import com.jiangli.utils.Sreach.SearchUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 菜品索引服务
 */
@Service
@Slf4j
public class IngredientIndexServiceImpl{

    @Autowired
    private GenericIndexService<Ingredient, Long> genericIndexService;

    @Autowired
    private DishMapper dishMapper;

    private static final int EXPIRE_HOURS = 24;
    @Autowired
    private IngredientMapper ingredientMapper;

    /**
     * 系统启动初始化索引
     */
    @PostConstruct
    public void initDishIndex() {
        //查询数据库
        log.info("初始化索引");
        List<Ingredient> allIngredient = ingredientMapper.selectAllAvailable();
        //创建索引
        genericIndexService.batchBuildIndex(
                allIngredient,
                Ingredient::getId,
                RedisKeyUtils.INGREDIENT_INFO,
                RedisKeyUtils.INGREDIENT_INDEX,
                this::getIngredientKeywords,
                EXPIRE_HOURS
        );
    }

    /**
     * 构建单个菜品索引
     */
    public void buildDishIndex(Ingredient ingredient) {
        genericIndexService.buildIndex(
                ingredient,
                Ingredient::getId,
                RedisKeyUtils.INGREDIENT_INFO,
                RedisKeyUtils.INGREDIENT_INDEX,
                this::getIngredientKeywords,
                EXPIRE_HOURS
        );
    }

    /**
     * 删除菜品索引
     */
    public void deleteIngredientIndex(Long ingredientId) {
        genericIndexService.deleteIndex(ingredientId, RedisKeyUtils.INGREDIENT_INFO);
    }

    /**
     * 获取菜品关键词 TODO 获取菜品哪里关键词
     */
    public List<String> getIngredientKeywords(Ingredient ingredient) {

        List<String> nameKeys = SearchUtils.ikSegment(ingredient.getName());
        //TODO 报错getcalories为null'
        //List<String> calories = new ArrayList<>(Collections.singleton(ingredient.getCalories().toString()));
        //nameKeys.addAll(calories);
        return nameKeys.stream().distinct().collect(Collectors.toList());
    }

    // 委托查询方法
    public Set<String> getIngredientIdsByKeyword(String keyword) {
        return genericIndexService.queryEntityIds(RedisKeyUtils.INGREDIENT_INDEX, keyword);
    }
//    // 获取实体 TODO 用已有的方法解决
//    public Dish getDishFromCache(Long dishId) {
//
//        return genericIndexService.getEntityFromCache(RedisKeyUtils.DISH_INFO, dishId, Dish.class);
//    }
}

